package view;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import model.BuyOrder;
import model.Order;
import server.Server;
import client.Client;

public class HistoryPanel extends JPanel {
	private static final long serialVersionUID = 6792781583088231674L;
	
	private JTextField fromBox, toBox;
	private JButton getHistory;
	private JTextArea history;

	private DateFormat dateFormat;
	
	private Server server;
	private Client client;

	
	/**
	 * Default constructor for the history panel
	 */
	public HistoryPanel() {
		
		dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
		Date now = new Date();
		fromBox = new JTextField(dateFormat.format(now));
		toBox = new JTextField(dateFormat.format(now));
		history = new JTextArea();
		getHistory = new JButton("get history");
		getHistory.addActionListener(new GetHistoryListener());

		setLayout(new BorderLayout());
		JPanel dateControls = new JPanel(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(5, 5, 5, 5);
		c.weightx = 0.5;
		c.gridy = 0;

		c.gridy++;
		dateControls.add(new JLabel("from"), c);
		dateControls.add(fromBox, c);

		c.gridy++;
		dateControls.add(new JLabel("to"), c);
		dateControls.add(toBox, c);

		c.gridy++;
		c.gridx = 1;
		dateControls.add(getHistory, c);

		add(dateControls, BorderLayout.NORTH);
		add(new JScrollPane(history), BorderLayout.CENTER);
	}
	
	/**
	 * Assign the current initialised objects to the un-initialised
	 * @param server
	 * 		The server object
	 * @param client
	 * 		The client object
	 */
	public void setup(Server server, Client client) {
		this.server = server;
		this.client = client;
	}
	
	/** Handles displaying the history **/
	public class GetHistoryListener implements ActionListener {

		public void actionPerformed(ActionEvent arg0) {
			try {
				// get the dates from the text fields
				Date a = dateFormat.parse(fromBox.getText());
				Date b = dateFormat.parse(toBox.getText());
				if(b.before(a))
					throw new Exception("From date cannot be before To date!");
				
				// create a calendar object based on b for further use
				Calendar c = new GregorianCalendar();
				c.setTime(b);
				c.set(Calendar.HOUR, 23);
				c.set(Calendar.MINUTE, 59);
				c.set(Calendar.SECOND, 59);
				c.set(Calendar.MILLISECOND, 999);
				
				// get the list of user history
				ArrayList<Order> orders = server.getUserHistory(client,
						a, c.getTime());
				
				history.setText("");
				
				// update the field if there is any relevant data
				for (Order o : orders) {
					history.append(String.format(
							"%s %d of %s for %d (tid: %s) (date: %s)\n", 
							(o instanceof BuyOrder) ? "bought" : "sold", 
							o.getNumber(), o.getStockName(), o.getPrice(), 
							o.getTransactionId(),
							dateFormat.format(o.getDate())
					));
				}
			} catch (RemoteException e) {
				JOptionPane.showMessageDialog(HistoryPanel.this,
						"An error occured while communicating with server: " + e.getMessage(),
						"Error", JOptionPane.ERROR_MESSAGE);
			} catch (ParseException e) {
				JOptionPane.showMessageDialog(HistoryPanel.this,
						"Invalid date format, please use dd/mm/yy", "Error",
						JOptionPane.ERROR_MESSAGE);
			} catch(Exception e) {
				JOptionPane.showMessageDialog(HistoryPanel.this,
					e.getMessage(), "Error",
					JOptionPane.ERROR_MESSAGE);
			}

		}

	}

}
